﻿using DG.Tweening;
using System;
using System.Collections.Generic;
using UnityEngine;

public class FocusController : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
           this.SetCamPosByGood();
        }
    }

    /// <summary>
    /// 加载物体时设置相机位置
    /// </summary>
    private void SetCamPosByGood()
    {
        List<GameObject> temp = new List<GameObject>();
        temp.Add(DrawRectangleMng.Instance.Target);
        Bounds objBound;
        objBound = GetObjsBound(temp);

        Transform cameraTransform = Camera.main.transform;

        float radio;
        float angle;

        if (objBound.size.x <= objBound.size.y)
        {
            radio = (objBound.size.y * 8) / 14;
            angle = 60f;
        }
        else
        {
            radio = (objBound.size.x * 8) / 14;
            float fov = cameraTransform.gameObject.GetComponent<Camera>().fieldOfView;
            float fovInRads = fov * Mathf.Deg2Rad;
            float horizontalFovInRads =
                2 * (float)Math.Atan(Mathf.Tan(fovInRads / 2) *
                                      cameraTransform.gameObject.GetComponent<Camera>().aspect);
            float horizontalFov = horizontalFovInRads * Mathf.Rad2Deg;
            angle = horizontalFov;
        }

        float distance = radio / Mathf.Tan((angle / 2) * Mathf.Deg2Rad);
        float overlookOffset = distance * (Mathf.Tan(Mathf.PI / 25.7f));

        Vector3 camPos = objBound.center;
        
        camPos.z -= (distance + objBound.size.z / 1.0f);
        camPos.y += overlookOffset;
        cameraTransform.DOMove(camPos, 1.0f, false);
        cameraTransform.DORotate(Vector3.zero, 1.0f);
    }

    /// <summary>
    /// 获取物体包围盒大小
    /// </summary>
    /// <param name="objsForCapture"></param>
    /// <returns></returns>
    public static Bounds GetObjsBound(List<GameObject> objsForCapture)
    {
        Vector3 boundCenter = Vector3.zero;
        List<Vector3> posList = new List<Vector3>();
        List<MeshFilter> meshComps = new List<MeshFilter>();
        foreach (GameObject obj in objsForCapture)
        {
            MeshFilter[] meshComp = obj.GetComponentsInChildren<MeshFilter>();
            if (meshComp != null)
            {
                meshComps.AddRange(meshComp);
            }
        }

        var vCount = 0;
        foreach (var item in meshComps)
        {
            Mesh mesh = item.mesh;
            Vector3[] vertexs = mesh.vertices;
            for (int i = 0; i < item.mesh.vertexCount; i++)
            {
                Vector3 wolrdPos = item.transform.localToWorldMatrix.MultiplyPoint(vertexs[i]);

                boundCenter += wolrdPos;
                vCount++;

                posList.Add(wolrdPos);
            }
        }

        Bounds bound = new Bounds();
        boundCenter /= vCount;

        bound.center = boundCenter;
        posList.ForEach((_) => { bound.Encapsulate(_); });
        return bound;
    }
}
